package com.hzh.cusviewdemo.Activity;

import static com.hzh.cusviewdemo.Music.PlayerManagerReceiver.status;

import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.cbman.roundimageview.RoundImageView;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hzh.cusviewdemo.Adapter.MusicListAdapter;
import com.hzh.cusviewdemo.Adapter.MySongMenuAdapter;
import com.hzh.cusviewdemo.Base.BaseActivity;
import com.hzh.cusviewdemo.Base.StaggeredItemDecoration;
import com.hzh.cusviewdemo.Bean.CheckKeyData;
import com.hzh.cusviewdemo.Bean.MusicInfoData;
import com.hzh.cusviewdemo.Bean.MusicSearchData;
import com.hzh.cusviewdemo.Bean.MyMusicData;
import com.hzh.cusviewdemo.Bean.MySongMenu;
import com.hzh.cusviewdemo.Fragment.PlayMusicFragment;
import com.hzh.cusviewdemo.Music.Constant;
import com.hzh.cusviewdemo.Music.MusicPlayService;
import com.hzh.cusviewdemo.Music.MyMusicUtil;
import com.hzh.cusviewdemo.Music.PlayerManagerReceiver;
import com.hzh.cusviewdemo.Music.TimeOverService;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Ui.CustomSeekBar;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.DialogUtils;
import com.hzh.cusviewdemo.Util.RSAUtil;
import com.hzh.cusviewdemo.Util.SugarUtils;
import com.hzh.cusviewdemo.Util.ThreadPoolManager;
import com.hzh.cusviewdemo.Util.TimeUtils;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;

import java.util.Date;
import java.util.List;

public class MusicActivity extends BaseActivity implements MusicPresenter {

    private RecyclerView am_song_menu_list; // 歌单列表
    private RecyclerView am_music_list;
    private LinearLayout am_pay_coffee;
    private LinearLayout am_about_app;
    private EditText am_edit;
    private ImageView am_img_search;
    private TextView am_tv_search;
    private TextView am_clear_edit;
    private TextView am_search;
    private TextView am_notice;
    private ImageView am_play;
    private TextView am_song_info;
    private TextView am_song_progress;
    private ProgressBar am_load_time;
    private CustomSeekBar am_seekbar;
    private RoundImageView am_cover_pic;

    private LinearLayout am_linear_time;
    private TextView am_key_time;

    private String lrcContent = ""; // 歌词文件

    private String songTitle = "听歌神器 - HZH For QJL";
    private boolean isPlayFragmentShow;
    private PlayMusicFragment mPlayFragment;

    public static final String ACTION_UPDATE_UI_MUSIC = "com.hzh.cusviewdemo.Activity.MusicActivity:action_update_ui_broad_cast";
    private HomeReceiver mReceiver;

    private boolean isStartPlayMusic = false; // 初始进来默认没开始播放音乐

    @Override
    public int getLayout() {
        return R.layout.activity_music;
    }

    @Override
    public void initView() {
        // 注册接收广播
        register();

        am_edit = findViewById(R.id.am_edit);
        am_img_search = findViewById(R.id.am_img_search);
        am_tv_search = findViewById(R.id.am_tv_search);
        am_clear_edit = findViewById(R.id.am_clear_edit);
        am_search = findViewById(R.id.am_search);
        am_notice = findViewById(R.id.am_notice);
        am_play = findViewById(R.id.am_play);
        am_song_info = findViewById(R.id.am_song_info);
        am_song_progress = findViewById(R.id.am_song_progress);
        am_seekbar = findViewById(R.id.am_seekbar);
        am_load_time = findViewById(R.id.am_load_time);
        am_cover_pic = findViewById(R.id.am_cover_pic);
        am_linear_time = findViewById(R.id.am_linear_time);
        am_key_time = findViewById(R.id.am_key_time);
        am_song_menu_list = findViewById(R.id.am_song_menu_list);
        am_pay_coffee = findViewById(R.id.am_pay_coffee);
        am_about_app = findViewById(R.id.am_about_app);

        am_notice.setOnClickListener(v -> {
            // 注意
            startActivity(new Intent(MusicActivity.this, MusicNoticeActivity.class));
        });

        am_tv_search.setOnClickListener(v -> startActivity(new Intent(MusicActivity.this, SearchActivity.class)));
        am_img_search.setOnClickListener(v -> {
            Intent intent = new Intent(MusicActivity.this, SearchActivity.class);
            intent.putExtra("TAG_IS_PLAYING", isStartPlayMusic);
            startActivity(intent);
        });

        am_edit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                ToSearchMusic();
                return false;
            }
            return false;
        });

        am_cover_pic.setOnClickListener(v -> showPlayingFragment());

        am_search.setOnClickListener(v -> ToSearchMusic());
        am_clear_edit.setOnClickListener(v -> {
            am_edit.setText("");
//            ToastUtils.showShort("已清除搜索！");
        });
        am_play.setOnClickListener(v -> {

            String musicUrl = MyMusicUtil.getStringShared(Constant.KEY_PATH);
            if (musicUrl.equals("")) {
                Log.e(Config.TAG, "musicUrl is null");
                Intent intent = new Intent();
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);
                sendBroadcast(intent);
                Toast.makeText(MusicActivity.this, "歌曲不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            //如果当前媒体在播放音乐状态，则图片显示暂停图片，按下播放键，则发送暂停媒体命令，图片显示播放图片。以此类推。
            if (status == Constant.STATUS_PAUSE) {
//                Log.e(Config.TAG, "status == Constant.STATUS_PAUSE");
//                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
//                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
//                intent.putExtra(Constant.KEY_TITLE, songTitle);
//                sendBroadcast(intent);

                /*if (MyMusicUtil.getStringShared(Constant.IS_PLAYING_MUSIC).equals("0")) {
                    // 未在播放音乐
                    MyMusicData musicDataByRid = SugarUtils.findMusicDataByRid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                    Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nPATH：" + MyMusicUtil.getStringShared(Constant.KEY_PATH));
                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                    intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
                    intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
                    intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                    sendBroadcast(intent);
                    MyMusicUtil.setShared(Constant.IS_PLAYING_MUSIC, "1");
                } else {
                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                    intent.putExtra(Constant.KEY_TITLE, songTitle);
                    sendBroadcast(intent);
                }*/

                MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nLAST PATH：" + musicDataByRid.getUrl());
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
                intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
                intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                sendBroadcast(intent);

            } else if (status == Constant.STATUS_PLAY) {
                Log.e(Config.TAG, "status == Constant.STATUS_PLAY");
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PAUSE);
                sendBroadcast(intent);
            } else {
                Log.e(Config.TAG, "status == " + status);
                //为停止状态时发送播放命令，并发送将要播放歌曲的路径
                setMusicName();
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, MyMusicUtil.getStringShared(Constant.KEY_PATH));
                sendBroadcast(intent);
            }
        });

        am_seekbar.setProgressListener(progress -> {
            Log.e(Config.TAG, "MA:进度改变");
            // 拖动进度
            Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
            intent.putExtra(Constant.COMMAND, Constant.COMMAND_PROGRESS);
            intent.putExtra(Constant.KEY_CURRENT, progress * 1000);
            sendBroadcast(intent);
        });

        am_pay_coffee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MusicActivity.this, PayCoffeeActivity.class));
            }
        });

        am_about_app.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MusicActivity.this, MusicNoticeActivity.class));
            }
        });

        am_music_list = findViewById(R.id.am_music_list);
        am_music_list.addItemDecoration(new StaggeredItemDecoration(this, 14));

        // 获取相应权限
        XXPermissions.with(this).permission(Permission.RECORD_AUDIO, Permission.WRITE_EXTERNAL_STORAGE).request((permissions, all) -> {
            if (all) {
            } else {
                ToastUtils.showShort("权限不够");
            }
        });

        // 免责声明
        showWarmingDialog();
        // 秘钥校验
        showCheckDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPlayStatus();
        showMySongMenuList();
        // 刷新播放页面的歌词

    }

    private void showMySongMenuList() {
        ThreadPoolManager.getInstance().execute(() -> {

            // 更新RID为SID。
            List<MyMusicData> musicDataList = SugarUtils.findMusicData();
            for (MyMusicData musicData : musicDataList) {
                if (!musicData.getSid().equals(musicData.getSid())) {
                    musicData.setRid(musicData.getSid());
                    musicData.save();
                }
            }

            List<MySongMenu> allMySongMenu = SugarUtils.getAllMySongMenu();
            // Log.e(Config.TAG, "allMenu: " + allMySongMenu);
            runOnUiThread(() -> {
                MySongMenuAdapter menuAdapter = new MySongMenuAdapter(MusicActivity.this, allMySongMenu);
                am_song_menu_list.setLayoutManager(new LinearLayoutManager(MusicActivity.this));
                am_song_menu_list.setAdapter(menuAdapter);
            });
        });
    }

    private void showCheckDialog() {
        if (MyMusicUtil.getStringShared(Constant.IS_AGREE_WARMING).equals("0")) {
            DialogUtils.showCheckKeyDialog(new DialogUtils.CheckKeyCallBack() {
                @Override
                public void onCheck(CustomDialog dialog, String key) {
                    checkKey(key, new OnCheckKeyListener() {
                        @Override
                        public void onCheckOk(String result) {
                            // 对result 解密
                            checkOk(key, result, dialog);
                        }

                        @Override
                        public void onCheckFail(String msg) {
                            DialogUtils.showErrorToast(msg);
                        }
                    });
                }

                @Override
                public void onQuit(CustomDialog dialog) {
                    AppUtils.exitApp();
                    dialog.dismiss();
                }
            });
        }
    }

    /**
     * checkoK prepare start
     *
     * @param result
     */
    private void checkOk(String key, String result, CustomDialog dialog) {
        WaitDialog.show("");
        new Thread(() -> {
            String decryptData = RSAUtil.decrypt(result);
            CheckKeyData checkKeyData = JSONObject.parseObject(decryptData, CheckKeyData.class);
            if (checkKeyData == null) {
                DialogUtils.showErrorToast("非法操作0x11");
                WaitDialog.dismiss();
                return;
            }
            if (!checkKeyData.getKey().equals(key)) {
                DialogUtils.showErrorToast("非法操作0x22");
                WaitDialog.dismiss();
                return;
            }
            if (!checkKeyData.getDeviceCode().equals(DialogUtils.getDeviceCode())) {
                DialogUtils.showErrorToast("非法操作0x33");
                WaitDialog.dismiss();
                return;
            }
            Date expireDate = com.blankj.utilcode.util.TimeUtils.string2Date(checkKeyData.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
            Date nowDate = new Date();
            if (expireDate.before(nowDate)) {
                DialogUtils.showErrorToast("已过期，请重新去获取秘钥~");
                WaitDialog.dismiss();
                return;
            }
            // 卡密正常处理
            MyMusicUtil.setShared(Constant.SAVE_USER_KEY, checkKeyData.getKey());
            DialogUtils.showSuccessToast("校验成功\n到期时间：" + checkKeyData.getExpireTime());
            // 开启倒计时服务
            Intent intent = new Intent(MusicActivity.this, TimeOverService.class);
            intent.putExtra("INTENT_QUIT_TIME", checkKeyData.getExpireTime());
            startService(intent);
            // 更新倒计时时间
            Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);    //接收广播为MusicUpdateMain
            musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_KEY_TIME);
            musicIntent.putExtra("KEY_EXPIRE_TIME", checkKeyData.getExpireTime());
            sendBroadcast(musicIntent);
            // 消失对应加载
            dialog.dismiss();
            WaitDialog.dismiss();

            // 检查更新
            checkAppUpdate();
        }).start();
    }

    /**
     * 检查更新
     */
    private void checkAppUpdate() {
        checkUpdate(data -> {
            if (data == null) {
                return;
            }
            DialogUtils.showYesOrNoTipDialog("更新通知", data.getAppInfo() + (!data.getAppInfo().isEmpty() ? "\n\n当前最新版本：" : "当前最新版本：") + data.getAppVersion(), "暂不更新", "前往更新", !data.getMust().equals("1"), new DialogUtils.YesOrNoDismissCallBack() {
                @Override
                public void onDone(CustomDialog dialog) {
                    // 跳转更新,当前Dialog不去除
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(data.getAppUrl()));
//                        if (intent.resolveActivity(getPackageManager()) == null) {
//                            DialogUtils.showSuccessToast("没有可以前往跳转链接的浏览器应用，无法更新\n已帮您复制更新链接，请自行前往第三方浏览器进行更新~");
//                            return;
//                        }
                    // 第三方浏览器更新
                    startActivity(intent);
                }

                @Override
                public void onCancel(CustomDialog dialog) {
                    // TODO NOTHING
                    dialog.dismiss();
                }
            });
        });
    }

    private void showWarmingDialog() {
        if (MyMusicUtil.getStringShared(Constant.IS_AGREE_WARMING).equals("1")) {
            // 未同意免责声明
            String content = "1.本APP所有资源均收集于互联网，如侵犯您的权益，请提供相关文件发邮至2371827579@qq.com作下架资源处理。" + "\n2.用户下载本APP仅供学习使用，不得进行非法使用。" + "\n3.为避免不正当使用或滥用本软件，请在进入APP后输入微信群内获取的秘钥开始使用。" + "\n4.无论任何人是否同意本免责声明，本APP开发者不对本APP所涉及的任何权益或出现的问题进行负责。" + "\n\n本APP免责声明于2024-07-10生效\n\n开发者：黄宗豪\n：18170014087";
            DialogUtils.showYesOrNoTipDialog("免责声明", content, "退出", "我知道了", new DialogUtils.YesOrNoDismissCallBack() {

                @Override
                public void onDone(CustomDialog dialog) {
                    MyMusicUtil.setShared(Constant.IS_AGREE_WARMING, "0");
                    dialog.dismiss();
                    showCheckDialog();
                }

                @Override
                public void onCancel(CustomDialog dialog) {
                    AppUtils.exitApp();
                    dialog.dismiss();
                }
            });
        }
    }

    private void showPlayingFragment() {
        if (isPlayFragmentShow) {
            return;
        }
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.fragment_slide_up, 0);
        if (mPlayFragment == null) {
            mPlayFragment = new PlayMusicFragment(isStartPlayMusic);
            ft.replace(android.R.id.content, mPlayFragment);
        } else {
            ft.show(mPlayFragment);
        }
        ft.commitAllowingStateLoss();
        mPlayFragment.reloadLrc();
        isPlayFragmentShow = true;
    }

    private void initPlayStatus() {
        int status = PlayerManagerReceiver.status;
        switch (status) {
            case Constant.STATUS_STOP:
                showPlayStatus(false);
                // seekBar.setProgress(0);
                break;
            case Constant.STATUS_PLAY:
                showPlayStatus(true);
                break;
            case Constant.STATUS_PAUSE:
                showPlayStatus(false);
                break;
            case Constant.STATUS_RUN:
                showPlayStatus(true);
                // seekBar.setMax(duration);
                // seekBar.setProgress(current);
                break;
        }
    }

    private void register() {
        // 执行
        Log.e(Config.TAG, "MusicActivity：register");
        mReceiver = new HomeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_UPDATE_UI_MUSIC);
        registerReceiver(mReceiver, intentFilter);
    }

    private void unRegister() {
        if (mReceiver != null) {
            Log.e(Config.TAG, "广播接收器被关闭");
            unregisterReceiver(mReceiver);
        }
    }

    private void ToSearchMusic() {
        String content = am_edit.getText().toString().trim();
        if (content.equals("")) {
            ToastUtils.showShort("额，啥都没有搜不了啊");
            return;
        }
        searchMusic(content, new OnSearchMusicListener() {
            @Override
            public void onGetMusicSuccess(List<MusicSearchData> result) {
                showList(result);
            }

            @Override
            public void onGetMusicFail(String msg) {
                ToastUtils.showShort(msg);
            }
        });
    }

    @Override
    public void initData() {
//        getMusicList(this, "民谣", new OnMusicListListener() {
//            @Override
//            public void onGetMusicSuccess(List<MusicResponse.AbsData> result) {
//                showList(result);
//            }
//
//            @Override
//            public void onGetMusicFail(String msg) {
//                ToastUtils.showShort(msg);
//            }
//        });
        // 获取今天推荐歌曲
//        getTodayMusic(this, new OnMusicListListener() {
//            @Override
//            public void onGetMusicSuccess(List<MusicResponse.AbsData> result) {
//                showList(result);
//            }
//
//            @Override
//            public void onGetMusicFail(String msg) {
//                ToastUtils.showShort(msg);
//                // format=mp4 bitrate=512 url=http://ar.player.rh01.sycdn.kuwo.cn/99da10c73853683e14f1fb434abb8619/638173c9/resource/m2/80/77/4142928232.mp4 sig=17793741267236008452 quality=MP4
//
//            }
//        });


    }

    private void showList(List<MusicSearchData> result) {
        MusicListAdapter musicListAdapter = new MusicListAdapter(result, MusicActivity.this);
        musicListAdapter.setOnMusicClickListener(item -> {
            // 发起搜索歌曲
            listenMusic(MusicActivity.this, item.getId(), new OnListenMusicListener() {
                @Override
                public void onListenSuccess(MusicInfoData data) {
                    MyMusicUtil.setShared(Constant.KEY_NAME, data.getSongname());
                    MyMusicUtil.setShared(Constant.KEY_SONGER, data.getSonger());
                    MyMusicUtil.setShared(Constant.KEY_PIC, data.getSongpic());
                    songTitle = data.getSongname() + " - " + data.getSonger();
                    setMusicName();
                    // 获取到musicUrl
                    // 先暂停
                    Intent stopIntent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    stopIntent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);
                    sendBroadcast(stopIntent);

                    MyMusicUtil.setShared(Constant.KEY_PATH, data.getSongurl());
                    MyMusicUtil.setShared(Constant.KEY_ID, String.valueOf(data.getSid()));
                    MyMusicUtil.setShared(Constant.KEY_TITLE, songTitle);

                    Log.e(Config.TAG, "MA:保存本地播放列表：" + data.getSongname());

                    MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(String.valueOf(data.getSid()));
                    MyMusicData nextData = new MyMusicData();
                    if (musicDataByRid == null) {
                        // 添加到本地播放列表
                        nextData.setRid(String.valueOf(data.getSid()));
                        nextData.setSid(data.getSid());
                        nextData.setName(data.getSongname());
                        nextData.setSonger(data.getSonger());
                        nextData.setTitle(songTitle);
                        nextData.setPic(data.getSongpic());
                        nextData.setUrl(data.getSongotherurl());
                        nextData.setLrc(data.getSonglrc());
                        nextData.setType("0"); // 顺序播放
                        nextData.setMenu("全部歌曲");
                        nextData.setCreateTime(com.blankj.utilcode.util.TimeUtils.getNowString());
                        SugarUtils.addMusicData(nextData);

                        // 更新歌单
                        MySongMenu songMenu = SugarUtils.getSongMenuByName("全部歌曲");
                        if (songMenu != null) {
                            songMenu.setNum(songMenu.getNum() + 1);
                            songMenu.setPic(data.getSongpic());
                            songMenu.setUpdateTime(com.blankj.utilcode.util.TimeUtils.getNowString());
                            songMenu.save();
                        }
                    } else {
                        musicDataByRid.setUrl(data.getSongotherurl());
                        musicDataByRid.save();
                    }

                    isStartPlayMusic = true;

                    // 通知
                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                    intent.putExtra(Constant.KEY_PATH, data.getSongotherurl());
                    intent.putExtra(Constant.KEY_ID, musicDataByRid == null ? nextData.getSid() : musicDataByRid.getSid());
                    intent.putExtra(Constant.KEY_TITLE, songTitle);
                    sendBroadcast(intent);
                }

                @Override
                public void onListenFail(String msg) {
                    ToastUtils.showShort(msg);
                }
            });


        });
        am_music_list.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        am_music_list.setAdapter(musicListAdapter);
    }

    private void setMusicName() {
        String musicName = MyMusicUtil.getStringShared(Constant.KEY_NAME);
        String musicSonger = MyMusicUtil.getStringShared(Constant.KEY_SONGER);
        if (musicName.equals("") && musicSonger.equals("")) {
            am_song_info.setText("听歌神器 - For QJL");
        } else {
            am_song_info.setText(musicName + " - " + musicSonger);
            am_load_time.setVisibility(View.VISIBLE);
        }
        am_song_progress.setText("00:00 / 00:00");
    }

    class HomeReceiver extends BroadcastReceiver {
        int status;
        int duration;
        int current;
        String currentSentence;
        String coverPic; // 封面图片

        @Override
        public void onReceive(Context context, Intent intent) {
            // setMusicName();
            status = intent.getIntExtra(Constant.STATUS, 0);
//            Log.d(Config.TAG, "onReceive: " + status);
            current = intent.getIntExtra(Constant.KEY_CURRENT, 0);
            duration = intent.getIntExtra(Constant.KEY_DURATION, 100);
            currentSentence = intent.getStringExtra(Constant.KEY_CURRENT_SENTENCE);
            coverPic = intent.getStringExtra(Constant.KEY_PIC);
            // 存储歌词文件

            switch (status) {
                case Constant.STATUS_UPDATE_MENU_LIST:
                    Log.e(Config.TAG, "收到更新列表消息");
                    // 更新歌单列表
                    showMySongMenuList();
                    break;
                case Constant.STATUS_CLICK_SEARCH_RESULT_PLAY:
                    setMusicName();
                    isStartPlayMusic = true;
                    // 显示PlayFragment  不与原来的显示fragment一套
                    // 更新歌单列表
                    showMySongMenuList();
                    break;
                case Constant.STATUS_UPDATE_KEY_TIME:
                    String expireTime = intent.getStringExtra("KEY_EXPIRE_TIME");
                    am_linear_time.setVisibility(View.VISIBLE);
                    if (expireTime.equals("0")) {
                        am_key_time.setText("秘钥到期：已到期~");
                        return;
                    }
                    am_key_time.setText("秘钥到期：" + expireTime);
                    break;
                case Constant.STATUS_STOP:
                    showPlayStatus(false);
                    am_seekbar.progress(0);
                    break;
                case Constant.STATUS_PLAY:
                    showPlayStatus(true);
                    break;
                case Constant.STATUS_PAUSE:
                    showPlayStatus(false);
                    break;
                case Constant.STATUS_RUN:
                    showPlayStatus(true);
                    am_song_progress.setText(TimeUtils.stampToDateS(current, "mm:ss") + " / " + TimeUtils.stampToDateS(duration, "mm:ss"));
                    am_seekbar.setMaxProgress(duration / 1000);
                    am_seekbar.progress(current / 1000);
                    am_song_info.setText(currentSentence);
                    // Log.e(Config.TAG, "歌曲时长：" + duration + "--当前进度：" + current);
                    break;
                case Constant.STATUS_LOAD_OK:
                    // 加载封面图片
                    Glide.with(MusicActivity.this).load(coverPic).placeholder(R.drawable.ic_logo).error(R.drawable.ic_logo).into(am_cover_pic);
                    lrcContent = intent.getStringExtra(Constant.KEY_LRC_LIST);
                    MyMusicUtil.setShared(Constant.KEY_LRC_LIST, lrcContent);
                    am_load_time.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }

        }

    }

    @Override
    public void onBackPressed() {
        if (mPlayFragment != null && isPlayFragmentShow) {
            hidePlayingFragment();
            return;
        }
        super.onBackPressed();
    }

    private void hidePlayingFragment() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(mPlayFragment);
        ft.commitAllowingStateLoss();
        isPlayFragmentShow = false;
    }

    public void showPlayStatus(boolean isPlay) {
        runOnUiThread(() -> am_play.setImageResource(isPlay ? R.drawable.ic_play_song : R.drawable.ic_stop_song));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegister();
    }
}